package com.cxm.top_forum.controller;

import com.cxm.top_forum.constent.Constent;
import com.cxm.top_forum.pojo.RespBean;
import com.cxm.top_forum.pojo.User;
import com.cxm.top_forum.pojo.req.LoginReq;
import com.cxm.top_forum.pojo.req.RegReq;
import com.cxm.top_forum.pojo.req.UpdatePassReq;
import com.cxm.top_forum.service.UserService;
import com.cxm.top_forum.util.Md5Util;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author cxm
 * @date 2021/8/6
 */
@Api("用户接口")
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private DefaultKaptcha defaultKaptcha;
    @Autowired
    private UserService userService;
    @Autowired
    private JavaMailSenderImpl javaMailSender;
    @Autowired
    private MailProperties mailProperties;

    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public RespBean login(@RequestBody LoginReq loginReq, HttpSession session) {
        return userService.login(loginReq,session);
    }


    @ApiOperation(value = "注册")
    @PostMapping("/reg")
    public RespBean reg(@RequestBody RegReq req, HttpSession session) {
        if (!req.getVerify().equals(session.getAttribute(Constent.SESSION_MAIL_VERIFY))) {
            return RespBean.fail("验证码错误");
        }

        if (!req.getPassword().equals(req.getCheckPass())) {
            return RespBean.fail("两次密码不一样");
        }

        if (userService.isEmailExist(req.getEmail())) {
            return RespBean.fail("邮箱已存在");
        }

        if (userService.isNameExist(req.getUsername())) {
            return RespBean.fail("用户名已存在");
        }

        userService.register(req);
        session.removeAttribute(Constent.SESSION_MAIL_VERIFY);
        return RespBean.success("注册成功");
    }

    @ApiOperation(value = "验证码")
    @GetMapping(value = "/captcha", produces = "image/jpeg")
    public void captcha(HttpServletRequest request , HttpServletResponse response){
        // 定义response输出类型为图片
        response.setDateHeader("Expires",0);
        // set standard HTTP/1.1 no-cache headers
        response.setHeader("Cache-Control","no-store, no-cache, must-revalidate");
        // set IE extended HTTP/1.1 no-cache headers (user addHeader)
        response.addHeader("Cache-Control","post-check=0, pre-check=0");
        // set standard HTTP/1.0 no-cache headers
        response.setHeader("Pragma","na-cache");
        // 返回图片
        response.setContentType("image/jpeg");

        //-----------生成验证码 begin
        // 获取验证码文本内容
        String text = defaultKaptcha.createText();
        System.out.println("验证码内容："+text);
        // 讲验证码内容放入session
        request.getSession().setAttribute(Constent.SESSION_CAPTCHA,text);
        BufferedImage image = defaultKaptcha.createImage(text);
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            ImageIO.write(image,"jpg",outputStream);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (outputStream!=null){
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation("获取邮箱验证码")
    @GetMapping("/sendMailVerify")
    @Async
    public RespBean sendMailVerify(String email, HttpSession session) {
        String verify = defaultKaptcha.createText();
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
            helper.setFrom(mailProperties.getUsername());
            helper.setTo(email);
            helper.setSubject("top论坛注册验证");
            helper.setText("您的验证码为：" + verify + " 十分钟内有效。");
            javaMailSender.send(mimeMessage);
            session.setAttribute(Constent.SESSION_MAIL_VERIFY,verify);
        }catch (Exception e) {
            e.printStackTrace();
            return RespBean.fail("验证码发送失败");
        }

        return RespBean.success("验证码发送成功，注意查收");
    }

    @ApiOperation("修改密码")
    @PostMapping("/updatePass")
    public RespBean updatePass(@RequestBody UpdatePassReq req) {
        User user = userService.getById(req.getUserId());
        if (!Md5Util.enCode(req.getOldPass()).equals(user.getPassword())) {
            return RespBean.fail("密码错误");
        }
        user.setPassword(Md5Util.enCode(req.getNewPass()));
        userService.updateById(user);
        return RespBean.success("修改成功");
    }

    @ApiOperation("获取所有用户")
    @GetMapping("/")
    public RespBean getUsers(){
        return RespBean.success(userService.list());
    }

    @ApiOperation("禁用或启用用户")
    @GetMapping("/enable")
    public RespBean enableUser(Long userId,Short status) {
        User user = userService.getById(userId);
        user.setStatus(status);
        userService.updateById(user);
        return RespBean.success("操作成功");
    }

}
